/**
 *
 */
package com.levy.spring.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.levy.entity.Resource;
import com.levy.entity.User;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 
 * @author levy.xia
 *
 */
@Service("securityManager")
public class SecurityManagerSupport implements UserDetailsService {

    /**
     * @see javax.persistence.EntityManagerFactory
     */
    @Autowired
    private EntityManagerFactory entityManagerFactory;

    /**
     * load user by user name.
     * @param userName user name
     * @return  user details
     */
    @SuppressWarnings("unchecked")
    public final UserDetails loadUserByUsername(final String userName) {

        EntityManager em = entityManagerFactory.createEntityManager();
        Query q = em.createNativeQuery("select * from users where username=?", User.class);
        q.setParameter(1, userName);
        List<User> users = q.getResultList();

        if (users.isEmpty()) {
            em.close();
            throw new UsernameNotFoundException("User " + userName + " has no GrantedAuthority");
        }

        User user = users.get(0);
        em.refresh(user);
        em.close();
        return user;
    }

    /**
     * load authorities of url.
     * @return  authorities of url
     */
    @SuppressWarnings("unchecked")
    public final Map<String, String> loadUrlAuthorities() {
        Map<String, String> urlAuthorities = new HashMap<String, String>();
        EntityManager em = entityManagerFactory.createEntityManager();

        Query q = em.createNativeQuery("select * from  dm_resource where type='URL'", Resource.class);

        List<Resource> urlResources = q.getResultList();
        //List<Resource> urlResources = getHibernateTemplate()
        // .find("FROM Resource resource WHERE resource.type = ?", "URL");
        for (Resource resource : urlResources) {
            urlAuthorities.put(resource.getValue(), resource.getRoleAuthorities());
        }
        em.close(); 
        return urlAuthorities;
    }


}
